package com.tlgen.receiver;

import com.tlgen.model.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author: tlgen
 * @Discription:
 */
@Component
public class MailReceiver {

    public static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    MailProperties mailProperties;

    @Autowired
    TemplateEngine templateEngine;

    @RabbitListener(queues = "tlgen.mail.registry")
    public void handler(Registry registry) {
        LOGGER.info(registry.toString());

        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);

        try {
            helper.setTo(registry.getEmail());
            helper.setFrom(mailProperties.getUsername());
            helper.setSubject("注册成功!");
            helper.setSentDate(new Date());

            //渲染模板
            Context context = new Context();
            context.setVariable("studentName", registry.getStudentName());
            context.setVariable("password", registry.getPassword());
            //String mail = templateEngine.process("mail", context);
            helper.setText(templateEngine.process("mail", context), true);
            javaMailSender.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            LOGGER.error("邮件发送失败!" + e.getMessage());
        }

    }
}
